<template>
  <div class="tw-librichcontents">
    <template v-if="contentData">
      <div v-if="hasTitle"
        class="tw-librichcontents-title">{{contentData.title}}</div>

      <div v-if="hasSubTitle"
        class="tw-librichcontents-subtitle">{{contentData.subTitle}}</div>

      <div v-if="hasOtherInfos"
        class="tw-librichcontents-infos"><span v-for="(info, index) in contentData.otherInfos"
          :key="index">{{info.name}}{{info.value}}</span></div>
      <div v-html="contentData.content"
        class="tw-librichcontents-con"
        v-if="contentData.content.length> 0">
      </div>

      <div v-if="contentData.attchments && contentData.attchments.length > 0" class="tw-librichattchments">
        <h3>附件下载：</h3>
        <div v-for="(attach, idx) in contentData.attchments" :key="idx">
          <a class="tw-librichattchments-attachlink" :download="attach.name" :href="attach.url">{{attach.name}}</a>
        </div>
      </div>
    </template>

    <tw-lib-nodata v-else />
  </div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import nodata from '../tw-lib-base/no-data/no-data'

export default {
  name: 'rich-contents',

  mixins: [style, nodata],

  props,

  data () {
    return {
      contentData: null,
      apiContent: null
    }
  },

  computed: {
    style () {
      return {
        titleColor: this.titleColor,
        titleFontSize: this.titleFontSize,
        titleIsBold: this.titleIsBold,
        titleBgColor: this.titleBgColor,
        titlePadding: this.titlePadding,
        titleLineHeight: this.titleLineHeight,
        titleFontFamily: this.titleFontFamily,
        titleShadow: this.titleShadow,
        titleAlign: this.titleAlign,
        subTitleColor: this.subTitleColor,
        subTitleFontSize: this.subTitleFontSize,
        subTitleIsBold: this.subTitleIsBold,
        subTitleBgColor: this.subTitleBgColor,
        subTitlePadding: this.subTitlePadding,
        subTitleLineHeight: this.subTitleLineHeight,
        subTitleFontFamily: this.subTitleFontFamily,
        subTitleShadow: this.subTitleShadow,
        subTitleAlign: this.subTitleAlign,
        otherInfosColor: this.otherInfosColor,
        otherInfosFontSize: this.otherInfosFontSize,
        otherInfosIsBold: this.otherInfosIsBold,
        otherInfosAlign: this.otherInfosAlign,
        titleMargin: this.titleMargin,
        subTitleMargin: this.subTitleMargin,
        otherInfosMargin: this.otherInfosMargin,
        contentLineHeight: this.contentLineHeight,
        otherInfoSpace: this.otherInfoSpace,
        contentColor: this.contentColor,
        contentFontSize: this.contentFontSize,
        contentBgColor: this.contentBgColor
      }
    }
  },

  methods: {
    setStyle () {
      let style = ''
      if (this.hasTitle) {
        style += `::root.tw-librichcontents .tw-librichcontents-title {
          color: ${this.titleColor};
          font-size: ${this.titleFontSize};
          font-weight: ${this.titleIsBold ? '700' : '400'};
          text-align: ${this.titleAlign};
          background: ${this.titleBgColor};
          line-height: ${this.titleLineHeight};
          padding: ${this.titlePadding};
          font-family: ${this.titleFontFamily};
          text-shadow: 0 2px ${this.titleShadow};
          margin-bottom: ${this.titleMargin};
        }`
      }

      if (this.hasSubTitle) {
        style += `
        ::root.tw-librichcontents .tw-librichcontents-subtitle {
          color: ${this.subTitleColor};
          font-size: ${this.subTitleFontSize};
          font-weight: ${this.subTitleIsBold ? '700' : '400'};
          text-align: ${this.subTitleAlign};
          background: ${this.subTitleBgColor};
          line-height: ${this.subTitleLineHeight};
          padding: ${this.subTitlePadding};
          font-family: ${this.subTitleFontFamily};
          text-shadow: 0 2px ${this.subTitleShadow};
          margin-bottom: ${this.subTitleMargin};
        }`
      }

      if (this.hasOtherInfos) {
        style += `
        ::root.tw-librichcontents .tw-librichcontents-infos {
          text-align: ${this.otherInfosAlign};
          margin-bottom: ${this.otherInfosMargin};
          font-weight: ${this.otherInfosIsBold ? '700' : '400'}
        }`

        style += `
        ::root.tw-librichcontents .tw-librichcontents-infos  span{
          font-size: ${this.otherInfosFontSize};
          color: ${this.otherInfosColor};
        }`

        style += `
        ::root.tw-librichcontents .tw-librichcontents-infos  span + span{
          margin-left: ${this.otherInfoSpace};
        }`
      }

      this.addStyle(style)
    },

    getContentListByPageId () {
      this.contentData = null

      window.axios.post(`${window.$twApp.gateway}/unified-portal/document/getDocumentListBySiteId`, {
        condition: {
          siteId: this.$siteConfig.siteId,
          // siteId: 'cF5j8CgLY3X7',
          pageId: this.pageId,
          status: '1'
        },
        orderList: ['createTime desc', 'lastModifyTime asc'],
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }).then(resp => {
        if (resp.data.serverResult.resultCode && resp.data.result && resp.data.result.list && resp.data.result.list[0]) {
          this.getContent(resp.data.result.list[0].documentId)
        }
      })
    },

    getContent (documentId) {
      this.contentData = null
      this.apiContent = null

      window.axios({
        method: 'get',
        url: `${window.$twApp.gateway}/unified-portal/document/get/${documentId || this.$ui.urlQuery.documentId}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {}
      }).then((response) => {
        const content = response.data.result

        if (content) {
          this.apiContent = {
            ...content,
            otherInfos: [
            ],
            attchments: []
          }

          if (content.author) {
            this.apiContent.otherInfos.push({
              name: '作者：',
              value: content.author
            })
          }

          if (content.source) {
            this.apiContent.otherInfos.push({
              name: '来源：',
              value: content.source
            })
          }

          if (content.createTime) {
            this.apiContent.otherInfos.push({
              name: '创建时间：',
              value: content.createTime
            })
          }

          if (content.files) {
            for (const file of content.files) {
              if (file) {
                this.apiContent.attchments.push({
                  name: file.substring(file.lastIndexOf('/') + 1),
                  url: /^(http|https)/.test(file) ? file : `${this.$twApp.docFileBaseUrl || this.$twApp.fileBaseUrl}${file.startsWith('/') ? file : '/' + file}`
                })
              }
            }
          }

          this.init()
        }
      })
    },

    init () {
      this.contentData = this.dataIsFromPortal ? this.apiContent : this.contents

      if (this.contentData) {
        this.contentData.content = this.contentData.content.replace(/src=['"](.+?)['"]/gm, (m, p1) => {
          if (p1.startsWith('http') || p1.startsWith('https')) {
            return `src="${p1}" `
          } else {
            return `src="${this.$twApp.docFileBaseUrl || this.$twApp.fileBaseUrl}${p1}" `
          }
        })

        if (this.contentData.attchments) {
          this.$emit('update:attchments', this.contentData.attchments)
        }
      }
    }
  },

  created () {
    if (this.dataIsFromPortal) {
      if (this.pageId) {
        this.getContentListByPageId()
      } else {
        this.getContent(this.documentId)
      }
    } else {
      this.init()
    }
  },

  watch: {
    pageId () {
      this.getContentListByPageId()
    },

    documentId (val) {
      this.getContent(val)
    },

    contents: {
      deep: true,
      handler () {
        this.init()
      }
    }
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
